package com.icim.xmtm.importer.service;

import java.lang.reflect.InvocationTargetException;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.SqlDateConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.icim.dao.RetTmCusPrdInDao;
import com.icim.dao.RetTmCusPrdIndtDao;
import com.icim.entity.Ret_tm_cus_prd_in;
import com.icim.entity.Ret_tm_cus_prd_indt;
import com.icim.exception.ICIMException;
import com.icim.util.TimeUtil;
import com.icim.xmtm.dao.CtSlimifshipboxDao;
import com.icim.xmtm.dao.CtSlimifshipproductDao;
import com.icim.xmtm.entity.CtSlimifShipProduct;
import com.icim.xmtm.entity.CtSlimifshipbox;

import static com.icim.def.ComDef.XMTM_FACTORY_NAME;

@Service("xmtmImportProductInService")
public class XmtmImportProductInService implements IXmtmImportProductInService {

	private static final Logger logger = LoggerFactory
			.getLogger(XmtmImportProductInService.class);

	@Resource
	private JdbcTemplate xmtmJdbcTemplate;

	@Resource
	private CtSlimifshipboxDao ctSlimifshipboxDao;

	@Resource
	private CtSlimifshipproductDao ctSlimifshipproductDao;

	@Resource
	private RetTmCusPrdInDao retTmCusPrdInDao;

	@Resource
	private RetTmCusPrdIndtDao retTmCusPrdIndtDao;

	public void setErrorMessage(CtSlimifshipbox fromBox, ICIMException ex) {
		ctSlimifshipboxDao.updateBoxReceiveflag(fromBox.getBoxname(), "N",
				TimeUtil.getCurrentTimestamp(), ex.getMessage());
	}

	@Override
	public void subMainProc() throws IllegalAccessException,
			InvocationTargetException {

		/*
		 * get boxes havn't received
		 */

		List<CtSlimifshipbox> fromBoxList = ctSlimifshipboxDao.queryNewBox(XMTM_FACTORY_NAME);//TODO

		/*
		 * loop boxes and get sheets in the box save sheets and save box
		 * 
		 * save one , commit one. if commmit success ==>update custom's record
		 * status. if error occurred ==> update custom's record errormessage
		 * column;
		 */

		for (CtSlimifshipbox fromBox : fromBoxList) {

			ICIMException icimException = null;

			try {

				subMainProc2(fromBox);

			} catch (Exception ex) {
				logger.error(ex.toString());
				icimException = new ICIMException(ex.getMessage(), ex);
			} finally {

				if (icimException != null) {
					setErrorMessage(fromBox, icimException);
				} else {
					ctSlimifshipboxDao.updateBoxReceiveflag(
							fromBox.getBoxname(), "Y",
							TimeUtil.getCurrentTimestamp(), "");
				}
			}

			logger.info("import successful");

		}

	}

	@Transactional("icimTransactionManager")
	private void subMainProc2(CtSlimifshipbox fromBox)
			throws IllegalAccessException, InvocationTargetException {
		String boxId = fromBox.getBoxname();

		List<CtSlimifShipProduct> fromSheetList = ctSlimifshipproductDao
				.listSheets(boxId,XMTM_FACTORY_NAME);//TODO

		ConvertUtils.register(new SqlDateConverter(null), Date.class);
		ConvertUtils.register(new SqlDateConverter(null), Timestamp.class);

		for (CtSlimifShipProduct fromSheet : fromSheetList) {
			Ret_tm_cus_prd_indt toSheet = new Ret_tm_cus_prd_indt();
			BeanUtils.copyProperties(toSheet, fromSheet);

			String productname = toSheet.getProductname();
			if (retTmCusPrdIndtDao.get(productname) == null) {
				retTmCusPrdIndtDao.save(toSheet);
			} else {
				retTmCusPrdIndtDao.update(toSheet);
			}

		}

		Ret_tm_cus_prd_in toBox = retTmCusPrdInDao.get(boxId);

		if (toBox == null) {
			toBox = new Ret_tm_cus_prd_in();
			BeanUtils.copyProperties(toBox, fromBox);
			toBox.setEventtime(fromBox.getEventtime());
			toBox.setDeliverytime(fromBox.getDeliverytime());
			toBox.setReceivestate("INSERT");
			toBox.setErrormessage("");
			toBox.setReceiveflag("Y");
			retTmCusPrdInDao.save(toBox);
		} else {
			BeanUtils.copyProperties(toBox, fromBox);
			toBox.setEventtime(fromBox.getEventtime());
			toBox.setDeliverytime(fromBox.getDeliverytime());
			toBox.setReceivestate("UPDATE");
			toBox.setErrormessage("");
			toBox.setReceiveflag("Y");
			retTmCusPrdInDao.update(toBox);
		}
	}
}
